package com.iyao_app.util;

import com.iyao_app.entry.User;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/11/17.
 */

public class DbUtil {

    public static void updateUserInfo(final User oldSqlEntity) {
        Realm realm = Realm.getDefaultInstance();

        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
               realm.copyToRealmOrUpdate(oldSqlEntity);
            }
        });
    }


    public static User getUser() {

        Realm realm = Realm.getDefaultInstance();
        User fromRealm = null;
        User user = realm.where(User.class).findFirst();
        if (user != null) {
            fromRealm = realm.copyFromRealm(user);
        }
        realm.close();
        return fromRealm;
    }

    public static void deleteUserInfo() {
        Realm realm = Realm.getDefaultInstance();
        //先查找到数据
        final RealmResults<User> userList = realm.where(User.class).findAll();
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                if (userList.size() > 0) {
                    userList.deleteFromRealm(0);
                }
            }
        });

        realm.close();
    }

    public static void clearDb() {
        deleteUserInfo();
    }
}
